<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\Redis;
use think\facade\Log;


class Logs extends Base

{
    protected $name = 'logs';

    public function getAddressAttr($value, $data)
    {
        $address = Redis::Instance()->hGet('ipAddress', $data['ip']);
        return $address ?: '';
    }

    /**
     * @param $Description - 写入信息
     * @param int $emp_id - ID
     * @param string $emp_name - 账号
     * 原点 2021年4月26日15:51:13 日志写入数据库
     */
    public static function adds($Description, $emp_id = 0, $emp_name = '系统', $business_id = '')
    {
        parent::create([
            'emp_id'      => $emp_id,
            'emp_name'    => $emp_name,
            'event'       => request()->action(),
            'create_time' => time(),
            'ip'          => request()->ip(),
            'description' => $Description
        ]);
    }

    /**
     * @param $route - 文件路径
     * @param $msg - 写入信息
     * 原点 2021年4月26日15:51:31 日志写入文件
     */

    public static function write($route, $msg)
    {
        $method = request()->controller() . '/' . request()->action();
        file_put_contents($route,
            "时间：" . date('Y-m-d H:i:s') . "\r\n
            状态：" . $msg . "\r\n
            IP：" . request()->ip() . "\r\n
            方法：" . $method . "\r\n",
            FILE_APPEND);
    }

    /**
     * 异常日志
     * @param \Exception $e
     * @param string $desc
     * @param false $trace
     */
    public static function exception(\Exception $e, $desc='', $trace=false): void
    {
        try {
            $arr = [
                'desc' => $desc ?: request()->controller().'/'.request()->action(),
                'msg' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ];
            $trace && $arr['trace'] = $e->getTrace();

            Log::write(json_encode($arr,JSON_UNESCAPED_UNICODE), 'exception');
        } catch (\Exception $e) {
            Log::write("Logs::exception", 'exception');
        }
    }
}
